package com.lovemanai.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.AsyncContext;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lovemanai.listener.MyAsyncListener;
import com.lovemanai.service.Executor;


//指定asyncSupported属性值为true，表示该Servlet支持异步处理
@WebServlet(urlPatterns="/async1", asyncSupported=true)
public class AsyncServlet1 extends HttpServlet implements Servlet {
	private static final long serialVersionUID = 1L;
 
    public AsyncServlet1() {
        super();
        
    }

	
	public void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		out.println("<h2>进入异步处理的时间：</h2>");
		out.println("" + new Date() + "<br/>");
		/*
		 * Servlet异步处理是让Servlet重新发起一个线程用以处理耗时的业务，达到避免等待的效果
		 */
		//获得AsyncContext对象，开始异步调用
		AsyncContext actx = request.startAsync();
		//注册异步调用监听器
		actx.addListener(new MyAsyncListener());
		//设置异步调用超时等待时间
		actx.setTimeout(1000 * 6);
		//启动调用异步线程
		actx.start(new Executor(actx));
		
		out.println("<h2>结束异步处理的时间：</h2>");
		out.println("" + new Date() + "<br/>");
		out.flush();
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		
	}

}
